$(function(){

	// 弹窗样式
	function layerCss(){
	    $(".layui-layer").css("border-radius","10px")
	    $(".layui-layer-setwin .layui-layer-close2").css({"right":"-40px","top":"0px"});
	    $(".layui-layer-ico").css("background","url("+jumpUrl+"/img/question2/iconlayer.png)");
	}
	// 如果是打赏获取律师id
	if (question_type == "打赏") {
		getPayInfo();
	}
	// 获取订单资料
	function getPayInfo(){
	    var wallet_url = jumpUrl+"/center/pay/question/"+in_question_id+"/view?type=1";
	    $.get(wallet_url,function(data){
		    },'json').success(function(data) {
		    var obj = data.data;
		    console.info(obj);
		    $(".pay-lv-id").text(obj.product_id);
		});
	}


	//付款请求
	$(document).on('click', '.submit-but', function(e){
		$(".content-box").html("");
		var loading = layer.msg('加载中...', {icon: 16});

		var lv_user_id = $(".pay-lv-id").text();
		var question_id = $(this).attr("data-id");
		var type = $('.checkedIcon').attr('data-href');
		var order_type = $("#type").text();
		var type_subject = $("#type").text();
		var type_body = $("#type").text();
		var view_url =  JSON.parse(localStorage.getItem('view_url'));
		if (order_type == "wallet_recharge") {
			var in_pay_type = "wallet_recharge"
		}else if(order_type == "打赏"){
			var in_pay_type = "wallet_reward"
		}else{
			var in_pay_type = "order"
		}
		if (type == "wallet") {
			if (order_type == "打赏") {
				 //提交打赏
	          	var url = jumpUrl+"/wallet/reward";
	          	$.post(url,{"money":totalMoney,"user_id":lv_user_id,"order_id":question_id},function(data){
			      },'json').error(function(data) {
			          var obj = $.parseJSON(data.responseText);
            		  layer.msg(obj.error_messages);
			      }).success(function(data) {
			      	 layer.msg("打赏成功");
			         window.location.href = view_url;
			      });
	        }else{
	          	var url = jumpUrl+"/center/question/"+question_id+"/pay/wallet";
	          	$.post(url,function(data){
			      },'json').error(function(data) {
			          var obj = $.parseJSON(data.responseText);
			          layer.msg(obj.error_messages);
			      }).success(function(data) {
			          layer.msg(data.data);
			          window.location.href=jumpUrl+"/center/customer/my_order";
			      });
	        }
		    
		}else if(type == "weixin"){
			var params = {};
			params.device = 'pc';   // 客户端
			params.channel = 'wx_pub_qr';   //支付方式
			params.amount = totalMoney*100;  //支付金额乘以100
			params.subject = type_subject;   //商品标题
			params.body = type_body;  //商品描述
			params.product_id = question_id;  //微信公众账号扫码支付 订单id
			params.current_user_id = current_user_id;  //当前id
			params.metadata = {};  
			params.metadata.pay_type = in_pay_type;  //订单类型
			if (order_type == "打赏") {
				params.metadata.user_id = lv_user_id;  // 收到心意的律师的id
				params.metadata.from_user_id = current_user_id;   //送出心意的用户的id
			}else{
				params.metadata.question_id = question_id;  //订单id
			}
			var wechat_qr_params_url = jumpUrl+"/payment_gateway/charge";
			var qr_code_url;
		    $.post(wechat_qr_params_url,params,function(data){
		      },'json').error(function(data) {
		          var obj = $.parseJSON(data.responseText);
		          layer.msg(obj.error_messages);
		      }).success(function(data) {
			      	console.log(data);
			      	qr_code_url = data.credential.wx_pub_qr;
			      	  charge_id = data.id;
			      	  qr_payment_popup();
			      	  check_payment(charge_id);
			      	  var str = ''
			      	  str +='<img src="http://paysdk.weixin.qq.com/example/qrcode.php?data='+qr_code_url+'" style="width:250px;height:250px;border-radius: 10px;" />';
			      	  str +='<p style="text-align:center;font-size:20px;">[ 扫描二维码支付 ]</p>';
			      	$(".content-box").append(str);
		      });
		}else if(type == "alipay"){
			var params = {};
			params.device = 'pc';  // 客户端
			params.channel = 'alipay_pc_direct';  //支付方式
			params.amount = totalMoney*100; //支付金额乘以100
			params.subject = type_subject;  //商品标题
			params.body = type_body;  //商品描述
			params.success_url = jumpUrl+"/payment_gateway/charge_succeeded";  //支付成功的回调地址
			params.current_user_id = current_user_id;  //当前id
			params.metadata = {};
			params.metadata.pay_type = in_pay_type;  //订单类型
			if (order_type == "打赏") {
				params.metadata.user_id = lv_user_id;  // 收到心意的律师的id
				params.metadata.from_user_id = current_user_id;   //送出心意的用户的id
			}else{
				params.metadata.question_id = question_id;  //订单id
			}
			var wechat_qr_params_url = jumpUrl+"/payment_gateway/charge";
			var qr_code_url;
		    $.post(wechat_qr_params_url,params,function(data){
		      },'json').error(function(data) {
		          var obj = $.parseJSON(data.responseText);
		          // layer.msg(obj.error_messages);
		          console.info(obj);
		          layer.msg("请选择其他付款类型");
		      }).success(function(data) {
			      	console.log(data);
			      	pingppPc.createPayment(data, function(result, err){
					    console.log(result);
					    console.log(err.msg);
					    console.log(err.extra);
					    if (result == "success") {
					        // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL。
					    } else if (result == "fail") {
					        // charge 不正确或者微信公众账号支付失败时会在此处返回
					    } else if (result == "cancel") {
					        // 微信公众账号支付取消支付
					    }
					});
		      });
		}else{
			layer.msg("请选择付款类型");
      		return false;
		}
		stopDefault(e);
	});

	function check_payment(charge_id){
		var t1;
		var sum =0;
		function update_notify(){
				sum++;
				if(sum>600){window.clearInterval(t1);return false;}
				if(sum>180){
					m = sum%10;
					if(m!=0){return false;}
				}
				$(".sum").html(sum);
				var payment_query_url = jumpUrl + '/payment_gateway/query/'+charge_id;
			    $.get(payment_query_url, function(data){
			          
		        }, "json").error(function(data) {
	                var status_code = $.parseJSON(data.responseText);
	                layer.msg(status_code.message);
		        }).success(function(data) {
					console.log(data);
		            var obj = data;
		            if(obj.paid==true) {
		            	layer.msg("购买成功");
		            	if (order_type == "打赏") {
		          			window.location.href = view_url;
				        }else{
				          	window.location.href=jumpUrl+"/center/customer/my_order";
				        }
			        }
		        });
			}
			t1 = window.setInterval(function() {
				popup_visible = $(".content-box").is(":visible");
				if (popup_visible) {
					update_notify();
				}
				console.log('isvisible', $(".content-box").is(":visible"));
			},1000);
		window.onblur = function(){
			clearInterval(t1);
		}
		window.onfocus = function(){
			t1 = setInterval(function(){
				popup_visible = $(".content-box").is(":visible");
				if (popup_visible) {
					update_notify();
				}else{
					stopDefault();
				}
				console.log('isvisible', $(".content-box").is(":visible"));
			}, 1000 );
		}
	};

	// 微信扫码付费弹出框
	function qr_payment_popup(){
	 	var Popup02 = $(".content-box");
	 	layer.open({
          type: 1, //基本层类型  可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）。 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
          title: false, //标题
          closeBtn: true,  //关闭按钮
          shade:0.3,  //遮罩默认是0.3透明度
          area: ['250px', '300px'],
          skin: 'yourclass', //样式类名
          content: Popup02 //内容
      	});
      	layerCss();
	};
	
});
